﻿/*serviceUrl*
 * @Description 基础框架服务调用实例-单表服务
 *@Author  guoyanfei
 */
var editState = 0;
var commServices = commServices || {};


var input_paramDict = new Map();
input_paramDict.set('serviceID', 'input_serviceId')
input_paramDict.set('pageNO','input_pageNO')
input_paramDict.set('pageSize', 'input_pageSize');
input_paramDict.set('appCode', 'input_appCode');


console.log("luowen- start Test ")
var postPath = '/gdp'

var url = postPath + '/business/singleServer/querySingleTB';

// var serviceUrl = "/gdp"
var preUrl = postPath


var singleColumns = [{
    title: '字段名称',
    field: 'fieldname',
    align: 'center',
    valign: 'middle'
}, {
    title: '中文名称',
    field: 'fieldnamecn',
    align: 'center',
    valign: 'middle',
    editable: true
}, {
    title: '字段类型',
    field: 'fieldtype',
    align: 'center',
    valign: 'middle'
}];

var fieldConditionColumnList= [{
    title: '字段名称',
    field: 'fieldname',
    align: 'center',
    valign: 'middle'
}, {
    title: '中文名称',
    field: 'fieldnameCn',
    align: 'center',
    valign: 'middle',
    editable: true
}, {
    title: '字段类型',
    field: 'fieldtype',
    align: 'center',
    valign: 'middle'
}];



var viewColumns = [{
        title: '表名',
        field: 'altername',
        align: 'center',
        valign: 'middle'
    },
    {
        title: '表字段',
        field: 'fieldname',
        align: 'center',
        valign: 'middle'
    }, {
        title: '中文名称',
        field: 'fieldnameCn',
        align: 'center',
        valign: 'middle'
    }, {
        title: '字段类型',
        field: 'fieldtype',
        align: 'center',
        valign: 'middle'
    }, {
        title: '视图字段',
        field: 'fieldname',
        align: 'center',
        valign: 'middle',
        formatter: function (value, row, index) {
            return row.altername + '_' + value
        }
    }];

commServices.prototype = {
    init: function () {//初始化
        commServices.prototype.IsPage();
        commServices.prototype.getTableData();
        commServices.prototype.setSearchColumn();
        commServices.prototype.eventSearch();
        commServices.prototype.eventExecuteBusinessService();
        // here is get all dynamic condition and set condition html
        commServices.prototype.handleDynamicConditionParameter();
        commServices.prototype.getFieldConditionTable();

    },
    IsPage: function () {
        console.log("luowen path " + postPath + '/business/singleServer/isPading')
        $.ajax({
            url: preUrl + '/business/singleServer/isPading',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            success: function (data) {
                isPageFormat = data.isPage;

                //             result.put("serviceType", cfgTable.getDtTabletype());
                if (data.serviceType === 2) {
                    commServices.prototype.getFieldTable('/system/dataView/getShowFieldListForPageViewByServiceId' ,viewColumns, serviceId);
                    if (data.isPage) {
                        commServices.prototype.createTablePage(serviceId);
                    }else {
                        commServices.prototype.createTable(serviceId);
                    }
                }else {
                    commServices.prototype.getFieldTable('/business/singleServer/queryTableShowField', singleColumns);
                    if (data.isPage) {
                        commServices.prototype.createTablePage();
                    }else {
                        commServices.prototype.createTable();
                    }
                }
            },
            error: function () {
                bootbox.alert("查询是否分页失败!");
            }
        });
    },
    createTablePage:function(serviceId){//创建分页表格
        $("#tb_list").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/business/singleServer/querySingleTB',
            undefinedText: '-',
            method: 'get',
            pagination: true,
            striped: true,
            cache: false,
            pageList: [5, 10, 20],
            toolbar: "#toolbar",
            showColumns: true,
            showRefresh: true,
            sidePagination: "server",
            responseHandler: function (res) {
                return handleResponseResult(res);
            },
            queryParams: commServices.prototype.queryParams,
            uniqueId: "guid",
            columns:  (!!serviceId ? commServices.prototype.getViewColumn(serviceId) : commServices.prototype.getTableColumn())
        });
    },
    createTable:function(serviceId){//创建不分页表格
        $("#tb_list").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/business/singleServer/querySingleTB',
            method: 'get',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            cache: false, // 是否使用缓存
            showColumns: true,
            showRefresh: true,
            responseHandler: function (res) {
                return handleResponseResult(res);
            },
            queryParams: commServices.prototype.queryParamsNoPageable,
            uniqueId: "guid", // 每一行的唯一标识
            columns:  (!!serviceId ? commServices.prototype.getViewColumn(serviceId) : commServices.prototype.getTableColumn())

        });
    },
    getFieldTable:function(url, columns, servicdId){//字段预览信息
        $("#tb_field").bootstrapTable({
            url: postPath + url,
            method: 'get',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色  
            cache: false, // 是否使用缓存 
            queryParams: { serviceID: serviceId} ,
            uniqueId: "guid", // 每一行的唯一标识
            columns: columns,
            onLoadSuccess: function () {//当所有数据被加载时触发处理函数
                if (!!serviceId){
                    var data = $("#tb_field").bootstrapTable('getData', true);//获取当前页数据
                    mergeCells(data,'altername',0,$("#tb_field"));
                }
            },
        });
    },

    getFieldConditionTable:function(){//字段预览信息
        var url = preUrl + '/system/queryfield/getQueryFieldList';

        console.log("luowen execute getFieldConditionTable, url", url, 'serviceId', serviceId)
        $("#tb_fieldCondition").bootstrapTable({
            url: url,
            method: 'get',
            undefinedText: '-',
            queryParams: {serviceId: serviceId, paramType: 1, serviceType: 1, grade: ''},
            uniqueId: "guid", // 每一行的唯一标识
            columns: fieldConditionColumnList
        });

        console.log("luowen execute getFieldConditionTable complete")

    },

    getTableData:function(){
        var tableData = new Array();
        $.ajax({
            url: postPath + '/business/singleServer/querySingleTB',
            type: 'get',
            async: false,
            data: { serviceID: serviceId,pageNO:1, pageSize:10},
            dataType: "json",
            success: function (data) {
                tableData = data;
            },
            error: function () {
                bootbox.alert("数据预览加载失败!");
            }
        });

    //    $("#tb_data").html(JSON.stringify(tableData));
    },
    getTableColumn:function(){//设置表格显示列
    	var coltxt = "{ field: 'state', checkbox: true, align: 'center', valign: 'middle' }";
        var columns = [];
        columns.push({ field: 'state', checkbox: true, align: 'center', valign: 'middle' });
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/singleServer/queryTableShowField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                bootbox.alert("显示列数据加载失败!");
            }
        });
        $.each(columnData, function (i, e) {
            columns.push({ "field": e.fieldname, "title": e.fieldnamecn, "align": 'center', "valign": 'middle' });
            coltxt +="<br/>   ,{ field: '"+e.fieldname+"', title: '"+e.fieldnamecn+"', align: 'center', valign: 'middle' }"
        });
        $("#s_col").html(coltxt);
        return columns;
    },

    getViewColumn: function(serviceId){

        var columns = [];
        //数据预览-创建表格
        $.ajax({
            url: postPath + '/system/dataView/getShowFieldListForPageViewByServiceId',
            type: 'POST',
            async: false,
            data: {serviceID: serviceId, num: Math.random()},
            success: function (data) {
                $.each(data, function (i, e) {
                    var field = "";
                    var fieldCn = "";
                    if (e.ismodfname == 1) {
                        field = e.modifieldname;
                    } else if (e.columnAlias != null && e.columnAlias != '') {
                        field = e.columnAlias
                    } else {
                        field = e.altername + '_' + e.fieldname;
                    }
                    if (null != e.fieldnameCn && e.fieldnameCn != "" && e.fieldnameCn != "null") {
                        fieldCn = e.fieldnameCn;
                    } else {
                        fieldCn =  "(" + e.altername + ")"+ e.fieldname;
                    }

                    if (e.ismodfcaption == 1) {
                        fieldCn = e.modifieldcaption;
                    } else {
                        fieldCn =  "(" + e.altername + ")"+ e.fieldnameCn;
                    }
                    columns.push({"field": field, "title": fieldCn, "align": 'center', "valign": 'middle'});
                });

            },
            error: function () {
                showMsg("数据加载失败!","error");
            }
        });

        return columns;
    },
    getColumnList: function () {//获取主表列数据
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/singleServer/queryTableField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data;
            },
            error: function () {
                bootbox.alert("列数据加载失败!");
            }
        });
        
        return columnData;
    },
    queryParams: function (pageReqeust) {//表格参数设置
        var temp = {
            serviceID: serviceId,
            pageNO: pageReqeust.offset / pageReqeust.limit + 1,
            pageSize: pageReqeust.limit,
            conQuery: commServices.prototype.setSearchParams(),
            from:'ADMIN'
        };
        return temp;
    },

    queryParamsNoPageable: function (pageReqeust) {//表格参数设置
        var temp = {
            serviceID: serviceId,
            conQuery: commServices.prototype.setSearchParams(),
        };
        return temp;
    },
    getPrimarykey: function () {//获取主键
        var strpk = "";
        $.ajax({
            url: postPath + '/business/singleServer/queryTableField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                $.each(data, function (i, e) {
                    if (e.dfIsprimarykey == 1) {
                        strpk = e.dfName;
                    }
                });
            },
            error: function () {
                bootbox.alert("主键获取失败!");
            }
        });
        return strpk;
    },
    setSearchColumn:function(){//设置查询列
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/singleServer/queryTableQueryField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                bootbox.alert("列数据加载失败!");
            }
        });
        if (columnData != null) {
            $.each(columnData, function (i, e) {
            	var fieldname = "search"+e.fieldname;
            	fieldname = fieldname.replace("@","_");
                switch (e.showtype) {
                    case "0"://文本框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='" + fieldname + "'>" + e.fieldnamecn + "：</label>");
                        $("#txtSearch").append("<input id='" + fieldname + "' placeholder='请输入" + e.fieldnamecn + "' type='text' class='form-control' >");
                        break;
                    case "1"://下拉框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='" + fieldname + "'>" + e.fieldnamecn + "：</label>");
                        var strtxt = "<select id='" + fieldname + "'  class='form-control' >"
                                       + "<option value=''>请选择</option>";
                        if (e.enumvalue != null && e.enumvalue != "") {
                            var enums = e.enumvalue.split(',');
                            for (var i = 0; i < enums.length; i++) {
                                var eb = enums[i].split(':');
                                strtxt += "<option value='"+eb[0]+"'>"+eb[1]+"</option>";
                            }
                        }
                        strtxt += "</select>";
                        $("#txtSearch").append(strtxt);
                        break;
                    case "4"://日期框
                        $("#txtSearch").append("<label style='margin-left:10px;' for='" + fieldname + "'>" + e.fieldnamecn + "：</label>");
                        $("#txtSearch").append("<input id='" + fieldname + "' data-date-format=\"yyyy-mm-dd\" type='text' class='form-control' >");
                        $("#" + fieldname + "").datetimepicker({language:'zh-CN'});
                        break;
                    case "6"://数字
                        $("#txtSearch").append("<label style='margin-left:10px;' for='" + fieldname + "'>" + e.fieldnamecn + "：</label>");
                        $("#txtSearch").append("<input id='" + fieldname + "' placeholder='请输入" + e.fieldnamecn + "' type='number' class='form-control' >");
                        break;
                }
            });
            
        }
    },
    setSearchParams:function(){//设置查询参数
        var searchParams = "";
        var columnData = new Array();
        $.ajax({
            url: postPath + '/business/singleServer/queryTableQueryField',
            type: 'get',
            async: false,
            data: { serviceID: serviceId },
            dataType: "json",
            success: function (data) {
                columnData = data.data;
            },
            error: function () {
                bootbox.alert("列数据加载失败!");
            }
        });
        if (columnData != null) {
            $.each(columnData, function (i, e) {
            	var fieldname = "search"+e.fieldname;
            	fieldname = fieldname.replace("@","_");
                if ($('#' + fieldname).val() != null && $('#' + fieldname).val() != 'undefined' && $('#' + fieldname).val() != "") {
                	  if (searchParams == "") {
                          searchParams = "\"" + e.fieldname + "\":\""+ $('#' + fieldname).val()+"\"";
                      } else { 
                          searchParams += ",\"" + e.fieldname + "\":\"" + $('#' + fieldname).val() + "\"";
                      }
                }
            });
            searchParams = "{" + searchParams + "}";
        }
        return searchParams;
    },
    eventSearch:function(){//查询操作
        $("#btn_search").click(function () {
            $("#tb_list").bootstrapTable('refresh');
        });
    },
    handleDynamicConditionParameter :function(){//查询操作
        console.log("luowen execute handleDynamicConditionParameter ")
        // here is get all condition item
        // http://localhost:9000/system/queryfield/getQueryFieldList?serviceId=localhost_GDP_singleTable_AIOV&serviceType=1&grade=&paramType=1
        var url = preUrl + '/system/queryfield/getQueryFieldList';

        // here assgin value to serviceId
        $("#input_serviceId").val(serviceId);

        console.log("luowen serviceID", serviceId)
        $.ajax({
            url: url,
            type: 'GET',
            data: {serviceId: serviceId, paramType: 1, serviceType: 1, grade: ''},
            success: function(data){
                if(data == null)
                    return;

                var appendHtml = "";
                data.forEach(function(e, i){
                    // create html object
                    var trObject = "<tr>";
                    trObject += "<td>" + e.fieldname + "</td>";
                    trObject += "<td>" + e.paramformat+ "</td>";
                    trObject += "<td>" + e.fieldnameCn + "</td>";
                    trObject += "<td>" + "<input type='text' style='width:100%' id=input_"+e.fieldname + " value = ''/> " + "</td>";
                    trObject += "</tr>"
                    // append
                    appendHtml += trObject;
                    input_paramDict.set(e.fieldname, "input_" + e.fieldname);
                });

                console.log("luowen appendHtml object", appendHtml)
                console.log("luowen input_paramDict", input_paramDict)
                $("#inputParameterList").append(appendHtml);
                // here is save input_param_
            },
            error: function(data){
                console.log("luowen fail dynamic condition parameter",data)
            }

        });

    },
    eventExecuteBusinessService:function(){//查询操作
        $("#btn_executeBusinessService").click(function () {
            // here is logic to expression all content
            // first section handle param
            // get general parameter
            var input_serviceId = $("#input_serviceId").val();
            var input_pageNO = $("#input_pageNO").val();
            var input_pageSize = $("#input_pageSize").val();
            console.log("luowen general input parameter", input_serviceId, input_pageNO, input_pageSize)
            $.ajax({
                url: preUrl + "/business/singleServer/querySingleTB",
                type: 'GET',
                data: getUrlInputParameter(),
                success: function(data){
                    console.log("luowen success execute response request", data)
                    generateCompleteUrl();
                    format_JS_code();
                    displayJsCodeResponse(data);

                },
                error: function(data){
                    console.log("luowen fail execute response request", data)

                }


            });


            // get conditon parameter
            // second section send request, and receive response
            // third section express result
            console.log("click business service")
        });
    },

    eventAdd: function () {//新增操作
        $("#btn_add").click(function () {
            $("#editTxt").html("");
            var columns = commServices.prototype.getColumnList();
            $.each(columns, function (i, e) {
                var addTxt = "<div class='form-group'><label class='col-md-3 control-label'>" + e.dfNameCn + "</label>";
                addTxt += "<div class='col-md-7'>";
                addTxt += "<input id='" + e.dfName + "' name='" + e.dfName + "' type='text' class='form-control input-inline input-medium' placeholder='请输入" + e.dfNameCn + "'>";
                addTxt += "</div></div>";
                $("#editTxt").append(addTxt);
            });
            editState = 1;
            $("#EditContent").modal('show');
        });
    },
    eventUpdate: function () {//修改操作
        $("#btn_edit").click(function () {
            var row = $('#tb_list').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请选择一行!");
                return;
            }
            $("#editTxt").html("");
            var columns = commServices.prototype.getColumnList();
            $.each(columns, function (i, e) {
                var addTxt = "<div class='form-group'><label class='col-md-3 control-label'>" + e.dfNameCn + "</label>";
                addTxt += "<div class='col-md-7'>";
                addTxt += "<input id='" + e.dfName + "' name='" + e.dfName + "' type='text' value='" + row[0][e.dfName] + "' class='form-control input-inline input-medium' placeholder='请输入" + e.dfNameCn + "'>";
                addTxt += "</div></div>";
                $("#editTxt").append(addTxt);
            });
            editState = 2;
            $("#EditContent").modal('show');

        });
    },
    eventSave: function () {//保存操作
        $("#btn_save").click(function () {
            var editUrl = "";
            if (editState == 1) {
                editUrl = postPath + "/business/singleServer/insertSingleTable";
            } else if (editState == 2) {
                editUrl = postPath + "/business/singleServer/updateSingleTable";
            }
            var temp = "{";
            var columns = commServices.prototype.getColumnList();
            $.each(columns, function (i, e) {
                temp += "\"" + e.dfName + "\":\"" + $('#' + e.dfName).val() + "\",";
            });
            temp = temp.substring(0, temp.length - 1);
            temp += "}";
            var jsonData = eval("(" + temp + ")");
            $.ajax({
                type: 'post',
                url: editUrl,
                async: false,
                data: { serviceID: serviceId, singleTBArrayJson: temp},
                dataType: 'json',
                success: function (res) {
                    if (res == true) {
                        bootbox.alert("保存成功!");
                        $('#tb_list').bootstrapTable('refresh');
                        $("#EditContent").modal('hide');
                    } else {
                        bootbox.alert("保存失败,请刷新后重试!");
                    }
                }
            });
        });
    },
    eventDel: function () {//删除操作
        $("#btn_del").click(function () {
            var row = $('#tb_list').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请选择一行或多行!");
                return;
            }
            bootbox.confirm("确认删除?", function (result) {
                if (result == false)
                    return;
                var strpk = commServices.prototype.getPrimarykey();
                var keys = "";
                $.each(row, function (i, e) {
                    keys += row[i][strpk] + ",";
                });
                keys = keys.substring(0, keys.length - 1);
                $.ajax({
                    url: postPath + "/business/singleServer/deleteSingleTable",
                    type: 'post',
                    data: { serviceID: serviceId,singleIDs:keys },
                    success: function (data) {
                        if (data == true) {
                            bootbox.alert("删除成功!");
                            $('#tb_list').bootstrapTable('refresh');
                        } else {
                            bootbox.alert("删除失败,请刷新后重新!");
                        }
                    },
                    error: function () {
                        bootbox.alert("删除失败!");
                    }
                });
            });
        });
    }
};

function mergeCells(data,fieldName,colspan,target){
    //声明一个map计算相同属性值在data对象出现的次数和
    var sortMap = {};
    for(var i = 0 ; i < data.length ; i++){
        for(var prop in data[i]){
            if(prop == fieldName){
                var key = data[i][prop]     //fieldName的value
                if(sortMap.hasOwnProperty(key)){
                    sortMap[key] = sortMap[key] * 1 + 1;
                } else {
                    sortMap[key] = 1;
                }
                break;
            }
        }
    }
    //合并单元格
    var index = 0;
    for(var prop in sortMap){
        var count = sortMap[prop] * 1;
        $(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});
        index += count;
    }
}

//服务初始化
$(function () {
    $("#sp_seviceUrl").append("服务地址：" + postPath + "/business/singleServer/querySingleTB");
    $("#sp_seviceUrl").append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;服务ID：" + serviceId);
    
    var comm = commServices.prototype;
    comm.init();


});


function getUrlInputParameter(){
    // here is build those object
    var inputParameter = {};
    input_paramDict.forEach((value, key) => {
        var inputValue = $("#" + value).val();
        if(inputValue == null || inputValue == undefined){
            inputValue = '';
        }
        var id = "#"+value;
        console.log("luowen map value", value, key, $(id).val(), id, inputValue)

        inputParameter[key] = inputValue
    });

    console.log("luowen final answer url parameter", inputParameter);
    return inputParameter;
}

function generateCompleteUrl(){
    var completeUrl = preUrl + "/business/singleServer/querySingleTB?"
    var formatParameter = getUrlInputParameter();
    console.log("luowen formatParameter", formatParameter)

    Object.keys(formatParameter).forEach( key => {
        completeUrl += "&" + key + "=" + formatParameter[key];
    })

//    var encodeUrl = encode_utf8(completeUrl);
    var encodeUrl = completeUrl;

    console.log("luowen encodeUrl", encodeUrl);
    $("#completeUrl").html(encodeUrl);
}

function encode_utf8(s) {
  return encodeURIComponent(s);
}

function format_JS_code(){
    var url = preUrl + "/business/singleServer/querySingleTB"
    var dataString = JSON.stringify(getUrlInputParameter());
    console.log("luowen dataString", dataString);

    var jsCode = "";
    jsCode += "\r\n$.ajax({";
    jsCode += "\r\n      url: " + url + ", ";
    jsCode += "\r\n      type: 'GET', ";
    jsCode += "\r\n      data: " + dataString + ", ";
    jsCode += "\r\n      success: function(responseData){" ;
    jsCode += "\r\n      }";
    jsCode += "\r\n})";

    console.log("luowen jsCode", jsCode)
    $("#generateJsCode").html(jsCode)
}

function displayJsCodeResponse(responseData){
    if(responseData == null)
        return;
    var responseContent = JSON.stringify(responseData, null, 2)
    console.log("luowen responseContent", responseContent)
    $("#displayJsCodeResponse").text(responseContent);
}
